package com.laicunba.service.activity.rewardimpl;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.laicunba.pojo.ActivityDO;
import com.laicunba.pojo.ActivityJoinDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.ActivityJoinService;
import com.laicunba.service.ActivityService;
import com.laicunba.service.RateIncrCouponDefService;
import com.laicunba.service.RateIncrCouponService;
import com.laicunba.service.activity.ActivityRewardService;
import com.laicunba.service.exception.MyException;
import com.laicunba.util.AssertUtil;

@Service
public class ActivityRewardRateCouponImpl implements ActivityRewardService {
	private static final String TYPE = "REWARD_RATE_COUPON";
	@Autowired
	private ActivityJoinService activityJoinService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private RateIncrCouponDefService rateIncrCouponDefService;

	@Override
	public String getType() {
		return TYPE;
	}

	@Override
	public boolean doReward(UserDO userDO, ActivityDO activityDO, ActivityJoinDO joinDO) {
		try {
			JSONObject json = (JSONObject) new JSONParser().parse(activityDO.getRewardReq());
			String defids = (String) json.get("defids");
			defids = "," + defids + ",";

			JSONObject req = (JSONObject) new JSONParser().parse(joinDO.getRewardReq());
			String defid = (String) req.get("defid");
			AssertUtil.assertTrue(defids.indexOf(defid) > -1, "DEF_ID_NOT_ALLOW");

			rateIncrCouponDefService.send2User(defid, userDO.getId(), false, "活动赠送");
			activityJoinService.updateStatusSuccess(joinDO.getId());
		} catch (MyException e) {
			AssertUtil.assertFail(e.getCode());
		} catch (Exception e) {
			AssertUtil.assertFail("DO_REWARD_FAIL");
		}
		return true;
	}

}
